using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using IGlobalist.Cms.Common;
using IGlobalist.Cms.Model;
using IGlobalist.Cms.Bll;
using System.Collections.Generic;
using System.IO;

namespace IGlobalist.Cms.Admin.Control
{
    public partial class ProductAddEdit : AdminBaseUserControl
    {
        public event EventHandler SaveContent;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                IList<IResourceFolder> resourceFolderList = ResourceFolderController.GetResourceFolderTreeForBind(0);
                resourceFolderList.RemoveAt(0);
                ddlFolderList.DataSource = resourceFolderList;
                ddlFolderList.DataTextField = "Name";
                ddlFolderList.DataValueField = "ID";
                ddlFolderList.DataBind();
                
                IList<ICmsClass> classList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.ResourceFile);
                ddlClassFileList.DataSource = classList;
                ddlClassFileList.DataTextField = "Name";
                ddlClassFileList.DataValueField = "ID";
                ddlClassFileList.DataBind();
                ddlImageThumNail.Attributes.Add("onchange", String.Format("JsProduct.showPreview(this,'{0}');", imgThumnail.ClientID));
                ddlImagePreView.Attributes.Add("onchange", String.Format("JsProduct.showThumnail(this,'{0}');", imgPreview.ClientID));
            }
        }

        public void DoBindContent(object sender, EventArgs e)
        {
            try
            {
                BindDllImage();                
                hdfClassID.Value = Convert.ToString(Session[SessionVariable.Clazz.CurrentID]);
                ProductListSummary pls = (ProductListSummary)sender;
                long contentID = Convert.ToInt64(pls.SelectedID);
                IProduct product = ProductController.GetProduct(contentID);
                BindProductEdit(product);
            }
            catch (Exception ex)
            {
                Logger.Debug("[[Error]]", ex);
            }
        }

        public void DoBindContentByProductDetail(object sender, EventArgs e)
        {
            try
            {
                BindDllImage();
                hdfClassID.Value = Convert.ToString(Session[SessionVariable.Clazz.CurrentID]);
                ProductViewDetail pvd = (ProductViewDetail)sender;
                long contentID = Convert.ToInt64(pvd.SelectedID);
                IProduct product = ProductController.GetProduct(contentID);
                BindProductEdit(product);
            }
            catch (Exception ex)
            {
                Logger.Debug("[[Error]]", ex);
            }
        }

        private void BindProductEdit(IProduct product)
        {
            lblStatus.Text = "Edit Product";
            ViewState["Product"] = product;
            ucCmsExtPropertiesForm.PropertyList = product.ExtPropertyList;
            
            tinyMCEContent.Text = product.Content;
            tinyMCESummary.Text = product.Summary;
            tbtag.Text = product.Tags;
            tbTitle.Text = product.Name;
            tbDiscount.Text = product.Discount.ToString();
            tbCode.Text = product.Code;
            tbSaler.Text = product.Seller;
            ddlClass.Enabled = false;
            tbPrice.Text = product.Price.ToString();
            tbPriceSale.Text = product.PriceSale.ToString();
            ddlLanguage.SelectedValue = product.Lang;
            ddlCategory.DataBind();
            ddlPage.DataBind();
            try
            {
                ddlPage.SelectedValue = product.PageID.ToString();
            }
            catch { }
            try
            {
                ddlCategory.SelectedValue = product.CategoryID.ToString();
            }
            catch { }

            try
            {
                ddlImageThumNail.SelectedIndex = -1;
                ddlImageThumNail.SelectedValue = product.ImageTN.ToString();
                imgThumnail.ImageUrl = String.Format("~/ImageView.aspx?id={0}&mdim=80", product.ImageTN);
            }
            catch { }
            try
            {
                ddlImagePreView.SelectedIndex = -1;
                ddlImagePreView.SelectedValue = product.ImagePV.ToString();
                imgPreview.ImageUrl = String.Format("~/ImageView.aspx?id={0}&mdim=80", product.ImageTN);
            }
            catch { }
        }

        public void DoCopyContent(object sender, EventArgs e)
        {
            ViewState["Product"] = null;
        }
        public void BindDllImage()
        {
            IList<IResourceFile> resourceFileList1 = ResourceFileController.GetResourceFileList(ResourceType.Image);
            ddlImagePreView.DataSource = resourceFileList1;
            ddlImagePreView.DataTextField = "Name";
            ddlImagePreView.DataValueField = "ID";
            ddlImagePreView.DataBind();
            

            IList<IResourceFile> resourceFileList2 = ResourceFileController.GetResourceFileList(ResourceType.Image);
            ddlImageThumNail.DataSource = resourceFileList2;
            ddlImageThumNail.DataTextField = "Name";
            ddlImageThumNail.DataValueField = "ID";
            ddlImageThumNail.DataBind();
            imgThumnail.ImageUrl = String.Format("~/ImageView.aspx?id={0}&mdim=80", resourceFileList1[0].ID);
            imgPreview.ImageUrl = String.Format("~/ImageView.aspx?id={0}&mdim=80", resourceFileList2[0].ID);
        }

        public void DoNewContent(object sender, EventArgs e)
        {
            lblStatus.Text = "Insert Product";
            if (Session[SessionVariable.Clazz.CurrentID] == null)
            {
                IList<ICmsClass> classList = ClassController.GetClassListByClassTypeID(11);
                if (classList.Count > 0)
                {
                    Session[SessionVariable.Clazz.CurrentID] = classList[0].ID;
                }
            }
            if (Session[SessionVariable.Clazz.CurrentID] != null)
            {
                BindDllImage();
                ddlClass.DataBind();
                ddlClass.Enabled = true;

                ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClass.SelectedValue));
                ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;
                ucCmsExtPropertiesForm2.PropertyList = clazz.PropertyList;
                if (ucCmsExtPropertiesForm.PropertyList.Count > 15)
                {
                    fsExtend.Visible = true;
                    fsExtenderProduct.Visible = true;
                }
                else
                {
                    fsExtend.Visible = false;
                    fsExtenderProduct.Visible = false;
                }

                ddlClass.SelectedValue = ddlClass.SelectedValue;
                hdfClassID.Value = Convert.ToString(ddlClass.SelectedValue);
                        
                tbSaler.Text = "";
                tinyMCEContent.Text = "";
                tinyMCESummary.Text = "";
                tbPrice.Text = "";
                tbCode.Text = "";
                tbDiscount.Text = "";                     
                tbPriceSale.Text = "";
                tbtag.Text = "";
                tbTitle.Text = "";
                tbTitle.Focus();
                ddlPage.DataBind();
                ddlCategory.DataBind();
                ViewState["Product"] = null;
            }      
        }

        public void DoHidden(object sender, EventArgs e)
        {
            Visible = false;
        }

        public void DoShow(object sender, EventArgs e)
        {
            Visible = true;
        }

        public void DoSaveContent(object sender, EventArgs e)
        {
            try
            {                
                IProduct product = new IGlobalist.Cms.Model.Product();
                if (ViewState["Product"] != null)
                {
                    product = (IProduct)ViewState["Product"];
                    product.EditedBy = IGlobalistMembership.GetUser().ID;
                }
                else
                {
                    product.Class = ClassController.GetClass(Convert.ToInt64(ddlClass.SelectedValue));
                    product.ClassID = Convert.ToInt64(ddlClass.SelectedValue);
                    product.ClassTypeID = Convert.ToInt16(CmsObjectType.Product);
                    product.CreatedDate = DateTime.Now;
                    product.Author = IGlobalistMembership.GetUser().ID;
                }
                product.Seller = tbSaler.Text;
                ucCmsExtPropertiesForm.PropertyList = product.ExtPropertyList;
                product.Description = "";
                product.Content = tinyMCEContent.Text;                    
                product.Name = tbTitle.Text;
                product.Summary = tinyMCESummary.Text;
                product.Discount = Convert.ToDouble(tbDiscount.Text);
                product.Code = tbCode.Text;
                if (String.IsNullOrEmpty(tbPrice.Text))
                {
                    product.Price = 0;
                }
                else
                {
                    product.Price = Convert.ToInt64(tbPrice.Text);
                }
                if (String.IsNullOrEmpty(tbPriceSale.Text))
                {
                    product.PriceSale = 0;
                }
                else
                {
                    product.PriceSale = Convert.ToInt64(tbPriceSale.Text);
                }
                ddlClass.Enabled = false;
                product.Tags = tbtag.Text;
                product.ImagePV = Convert.ToInt64(ddlImagePreView.SelectedValue);
                product.ImageTN = Convert.ToInt64(ddlImageThumNail.SelectedValue);
                product.Lang = ddlLanguage.SelectedValue;
                product.PageID = Convert.ToInt64(ddlPage.SelectedValue);
                product.CategoryID = Convert.ToInt64(ddlCategory.SelectedValue);
                product.Status = ContentStatus.Creating;
                if (ViewState["Product"] != null)
                    ProductController.UpdateProduct(product);
                else
                    ProductController.InsertProduct(product);
                ViewState["contentNoteList"] = null;
                
                if (SaveContent != null)
                {
                    SaveContent(this, new EventArgs());
                }
               
            }
            catch (Exception ex)
            {
                Logger.Debug("[[Error]]", ex);
                if (SaveContent != null)
                {
                    SaveContent(this, new EventArgs());
                }
            }
        }

        public void DoSendApproverContent(object sender, EventArgs e)
        {
            if (ViewState["Product"] != null)
            {
                IProduct product = (IProduct)ViewState["Product"];
                product.Status = ContentStatus.Approving;
                ProductController.UpdateProduct(product);

            }
        }

        public void DoSendEditContent(object sender, EventArgs e)
        {
            if (ViewState["Product"] != null)
            {
                IProduct product = (IProduct)ViewState["Product"];
                product.Status = ContentStatus.Approving;
                ProductController.UpdateProduct(product);

            }
        }

        public void DoSendAuthorContent(object sender, EventArgs e)
        {
            if (ViewState["Product"] != null)
            {
                IProduct product = (IProduct)ViewState["Product"];
                product.Status = ContentStatus.Approving;
                ProductController.UpdateProduct(product);
            }
        }

        public void DoPulicContent(object sender, EventArgs e)
        {
            if (ViewState["Product"] != null)
            {
                IProduct product = (IProduct)ViewState["Product"];
                product.Status = ContentStatus.Approving;
                product.CreatedDate =DateTime.Now;                
                ProductController.UpdateProduct(product);
                
            }
        }

        protected void btnUploadImageThumnail_Click(object sender, EventArgs e)
        {
            pnlProductAddEdit.Visible = false;
            pnlUploadImage.Visible = true;
        }

        protected void btnUploadImagePreView_Click(object sender, EventArgs e)
        {
            pnlProductAddEdit.Visible = false;
            pnlUploadImage.Visible = true;
            IList<ICmsClass> classList = ClassController.GetClassListByClassTypeID((short)CmsObjectType.ResourceFile);
            ucCmsExtPropertiesForm2.PropertyList = classList[0].PropertyList;
        }

        public void DoSaveFile(object sender, EventArgs e)
        {
            if (fuFile.HasFile && ddlImageType.SelectedIndex != 0)
            {
                string path = Path.Combine(DataRootPhysicalPath, "FileUpload");
                HttpPostedFile fPost = fuFile.PostedFile;
                string fName = fuFile.FileName;
                string fExtention = Path.GetExtension(fPost.FileName);
                long fSize = Convert.ToInt64(fPost.ContentLength);
                IResourceFile resourceFile = new ResourceFile();
                resourceFile.ExtPropertyList = ucCmsExtPropertiesForm2.PropertyList;
                resourceFile.Class = ClassController.GetClass(Convert.ToInt64(ddlClassFileList.SelectedValue));
                resourceFile.ClassID = Convert.ToInt64(ddlClassFileList.SelectedValue);
                resourceFile.FolderID = Convert.ToInt64(ddlFolderList.SelectedValue);
                resourceFile.ClassTypeID = (short)CmsObjectType.ResourceFile;
                resourceFile.Extention = fExtention;
                resourceFile.Type = (ResourceType)Convert.ToInt32(ddlImageType.SelectedValue);
                resourceFile.Name = fName;
                resourceFile.Size = fSize;
                resourceFile.UploadDate = DateTime.Now;
                resourceFile.EditedDate = DateTime.Now;
                resourceFile.Author = IGlobalistMembership.GetUser().ID;
                long numLongSave = ResourceFileController.InsertResourceFile(resourceFile);
                fPost.SaveAs(Path.Combine(path, numLongSave + fExtention));
                pnlUploadImage.Visible = false;
                pnlProductAddEdit.Visible = true;
                BindDllImage();
                ddlClass.Enabled = false;
            }

        }

        public void Cancel_event(object sender, EventArgs e)
        {
            pnlProductAddEdit.Visible = true;
            pnlUploadImage.Visible = false;
        }

        protected void ddlClassPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session[SessionVariable.Clazz.CurrentID] = ddlClass.SelectedValue;
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClass.SelectedValue));
            ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;
            ucCmsExtPropertiesForm2.PropertyList = clazz.PropertyList;
            if (ucCmsExtPropertiesForm.PropertyList.Count > 15)
            {
                fsExtend.Visible = true;
                fsExtenderProduct.Visible = true;
            }
            else
            {
                fsExtend.Visible = false;
                fsExtenderProduct.Visible = false;
            }           
        }
    }
}